﻿namespace CodePlex.Logistics.Web.Models
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using CodePlex.Logistics.Models;
using CodePlex.Logistics.Web.Models;
    using System.Security.Claims;
    using Microsoft.Owin.Security;
    using Microsoft.AspNet.Identity;

    public class UserAccountController : Controller
    {
        private LogisticsEntities db = new LogisticsEntities();

        // GET: /UserAccount/
        public ActionResult Index()
        {
            var useraccounts = db.UserAccounts.Include(u => u.Company);
            return View(useraccounts.ToList());
        }

        // GET: /UserAccount/Details/5
        public ActionResult Details(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserAccount useraccount = db.UserAccounts.Find(id);
            if (useraccount == null)
            {
                return HttpNotFound();
            }
            return View(useraccount);
        }

        // GET: /UserAccount/Create
        public ActionResult Create()
        {
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name");
            return View();
        }

        // POST: /UserAccount/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Username,PasswordHash,PasswordSalt,DateActive,DateInactive,Status,CompanyId")] UserAccount useraccount)
        {
            if (ModelState.IsValid)
            {
                useraccount.Id = Guid.NewGuid();
                db.UserAccounts.Add(useraccount);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", useraccount.CompanyId);
            return View(useraccount);
        }

        // GET: /UserAccount/Edit/5
        public ActionResult Edit(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserAccount useraccount = db.UserAccounts.Find(id);
            if (useraccount == null)
            {
                return HttpNotFound();
            }
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", useraccount.CompanyId);
            return View(useraccount);
        }

        // POST: /UserAccount/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Username,PasswordHash,PasswordSalt,DateActive,DateInactive,Status,CompanyId")] UserAccount useraccount)
        {
            if (ModelState.IsValid)
            {
                db.Entry(useraccount).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.CompanyId = new SelectList(db.Companies, "Id", "Name", useraccount.CompanyId);
            return View(useraccount);
        }

        // GET: /UserAccount/Delete/5
        public ActionResult Delete(Guid? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            UserAccount useraccount = db.UserAccounts.Find(id);
            if (useraccount == null)
            {
                return HttpNotFound();
            }
            return View(useraccount);
        }

        // POST: /UserAccount/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(Guid id)
        {
            UserAccount useraccount = db.UserAccounts.Find(id);
            db.UserAccounts.Remove(useraccount);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        public ActionResult Login()
        {
            return View(new LoginViewModel());
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel model)
        {
            ViewBag.Message = "POST Login";

            ViewBag.Alert = new AlertViewModel
            {
                AlertType = AlertViewModel.ViewModelAlertType.Info,
                Message = "POST Login"
            };
            
            // TODO: Perform user credentials validation
            // TODO: Perform user credentials authentication

            //ClaimsIdentity userClaimsIdentity = IdentityDataStore.GetClaimIdentity(model.UserName, model.Password);
            ////////////////////////////////////////////////////////////////////////////////
            // Create ClaimsIdentity

            // Add claims for username
            List<Claim> claims = new List<Claim>();
            claims.Add(new Claim(ClaimTypes.Name, "Ong Zhi Xian"));
            claims.Add(new Claim(ClaimTypes.NameIdentifier, "zhixian"));
            claims.Add(new Claim(ClaimTypes.Role, "SysAdmin"));
            claims.Add(new Claim(ClaimTypes.Role, "User"));

            ClaimsIdentity userClaimsIdentity = new ClaimsIdentity(
                claims, DefaultAuthenticationTypes.ApplicationCookie);

            if (userClaimsIdentity == null)
            {
                ViewBag.Alert = new AlertViewModel
                {
                    AlertType = AlertViewModel.ViewModelAlertType.Danger,
                    Message = "Invalid credentials"
                };
                return View(model);
            }

            var ctx = Request.GetOwinContext();
            var authenticationManager = ctx.Authentication;
            authenticationManager.SignIn(new AuthenticationProperties()
            {
                IsPersistent = true
            }, userClaimsIdentity);

            //SessionHelper.SelectiveSessionReset();
            //if (!string.IsNullOrEmpty(model.Url))
            //{
            //    return Redirect(model.Url);
            //}
            //return RedirectToAction("Index", "Home");

            return View(model);
        }
    }
}
